<template>
  <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px">
    <el-form-item label="账户">
      <el-input v-model="loginForm.username"></el-input>
    </el-form-item>

    <el-form-item label="密码">
      <el-input :type="pwdType" v-model="loginForm.password"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">登录</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>
  <script>
    import { isvalidUsername } from '@/utils/validate'

    export default {
      data() {
        const validateUsername = (rules, value, callback) => {
          if (!isvalidUsername(value)) {
            callback(new Error('请输入正确的用户名'))
          } else {
            callback()
          }
        }
        const validatePass = (rules, value, callback) => {
          if (value.length < 5) {
            callback(new Error('密码不能小于5位'))
          } else {
            callback()
          }
        }
        return {
          loginForm: {
            username: '',
            password: ''
          },
          loginRules: {
            username: [{ required: true, trigger: 'blur', validator: validateUsername }],
            password: [{ required: true, trigger: 'blur', validator: validatePass }]
          },
          loading: false,
          pwdType: 'password'
        }
      },
      methods: {
        showPwd() {
          if (this.pwdType === 'password') {
            this.pwdType = ''
          }  else {
            this.pwdType == 'password'
          }
        },
        onSubmit() {
          this.$refs.loginForm.validate(valid => {
            if (valid) {
              this.loading = true
              this.$store.dispatch('Login',this.loginForm).then(() => {
                this.loading = false
                console.log('login is success and return success')
                this.$router.push({path: '/'})
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
        }
      }
    }
  </script>
